﻿using Croton.Common.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Croton.Common.Controllers
{
    public class ImageController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="doubanid"></param>
        /// <param name="filesize">small,large,medium</param>
        /// <param name="defaulturl"></param>
        /// <returns></returns>
        public dynamic GetImage(string doubanid,string filesize,string defaulturl= "")
        {
            try
            {
                var ossFile = OssHelper.CheckFileExists(string.Format("tvplay/{0}/{1}{2}", doubanid, filesize, ".jpg"));
                if (!string.IsNullOrEmpty(ossFile))
                {
                    return Redirect(ossFile);
                }
                else
                {
                    var images = DoubanHelper.GetTVImagesById(doubanid);
                    Dictionary<string, string> imageurls = new Dictionary<string, string>();
                    foreach (var img in images)
                    {
                        using (var client = new HttpClient())
                        {
                            var fullname = string.Format("tvplay/{0}/{1}{2}", doubanid, img.Key, ".jpg");
                            var result = client.GetByteArrayAsync(img.Value).Result;
                            var streem = new MemoryStream(result);
                            var url = OssHelper.UploadFile(streem, fullname, "image/jpeg");
                            imageurls.Add(img.Key, url);
                        }
                    }
                    if (imageurls.Keys.Contains(filesize) && !string.IsNullOrEmpty(images[filesize]))
                    {
                        return Redirect(imageurls[filesize]);
                    }
                    else
                    {
                        return Redirect(defaulturl);
                    }
                }
                
            }
            catch (Exception ex)
            {
                //Log Exception
                Console.WriteLine(ex.Message);
                return Redirect(defaulturl);
            }
           
        }
    }
}
